package com.pqc.tbk.web.scheduling;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.pqc.tbk.service.taobao.TaoBaoService;
import com.taobao.api.domain.TaobaokeReport;
import com.taobao.api.domain.TaobaokeReportMember;

public class SystemJob implements ServletContextListener {

	private TaoBaoService taoBaoService;
	private Timer timer = null;
	private static Logger logger = Logger.getLogger(SystemJob.class);

	@Override
	public void contextInitialized(final ServletContextEvent sce) {
		logger.info("任务启动：每日订单下载");
		// 一天的毫秒数
		final long period = 24 * 60 * 60 * 1000L;
		// 计算当前时间离0点还有多少ms
		// 28800000是因为System.currentTimeMillis()是从1970年1月1日8点开始，需要加上8个小时的毫秒数
		final long delay = period
				- ((System.currentTimeMillis() + (7 * 60 * 60 * 1000L)) % period);//
		// 延迟到第二天01:00执行
		timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				taoBaoService = (TaoBaoService) WebApplicationContextUtils
						.getWebApplicationContext(sce.getServletContext())
						.getBean("taoBaoServiceImpl");
				System.out.println("系统任务调度" + taoBaoService + "test");
				long time = System.currentTimeMillis();
				time -= 86400000L;
				final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				final String today = sdf.format(new Date(time));
				final TaobaokeReport report = taoBaoService
						.getReport(today,
								"610210011e86861f1b510e305784dfa355512aae2a210e4720570431");
				// write into logs
				final long total = report.getTotalResults();
				System.out.println(total);
				if (total != 0) {

					logger.info(today + "共有" + total + "张订单");
					for (final TaobaokeReportMember member : report
							.getTaobaokeReportMembers()) {
						try {
							taoBaoService.saveReport(member);
						}
						catch (final Exception e) {
							logger.info("报表保存失败： {" + "推广人id："
									+ member.getOuterCode() + "佣金："
									+ member.getCommission() + "交易单号："
									+ member.getTradeId() + "}");
						}
					}
				} else {
					logger.info(today + ": 没有订单");
				}
			}
		}, delay, period);

	}

	@Override
	public void contextDestroyed(final ServletContextEvent sce) {
		if (timer != null) {
			timer.cancel();
		}
		logger.info("任务关闭...");
	}
}